import { useState, useEffect } from 'react';
import { X, Video, Mic, Image, Type, Settings, Sparkles } from 'lucide-react';
import type { VideoGenerateRequest } from '../../types/video';
import videoService from '../../services/videoService';
import avatarService from '../../services/avatarService';
import previewService, { type Voice } from '../../services/previewService';
import type { AvatarGroup, Avatar } from '../../types/avatar';
import VideoStatusTracker from '../VideoStatusTracker';
import { toast } from '../../stores/toastStore';

// Import sub-components
import ScriptTab from './ScriptTab';
import AvatarTab from './AvatarTab';
import VoiceTab from './VoiceTab';
import SettingsTab from './SettingsTab';
import PreviewPanel from './PreviewPanel';

interface VideoGenerateProps {
  onClose: () => void;
  onSuccess?: (videoId: string) => void;
}

// Convert Voice to simplified options for backward compatibility
const convertVoicesToOptions = (voices: Voice[]) => {
  return voices.map(voice => ({
    id: voice.voice_id,
    name: `${voice.name} (${voice.language})`,
    language: voice.language_code,
  }));
};

export default function VideoGenerate({ onClose, onSuccess }: VideoGenerateProps) {
  const [formData, setFormData] = useState<VideoGenerateRequest>({
    script: '',
    title: '',
    aspect_ratio: '16:9',
  });
  const [activeTab, setActiveTab] = useState('script');
  const [generating, setGenerating] = useState(false);
  const [generatedVideoId, setGeneratedVideoId] = useState<string | null>(null);
  const [showStatusTracker, setShowStatusTracker] = useState(false);

  // Avatar related states
  const [avatarGroups, setAvatarGroups] = useState<AvatarGroup[]>([]);
  const [avatarsInGroup, setAvatarsInGroup] = useState<Avatar[]>([]);
  const [selectedGroupId, setSelectedGroupId] = useState<string>('');
  const [selectedAvatar, setSelectedAvatar] = useState<Avatar | null>(null);
  const [loadingAvatars, setLoadingAvatars] = useState(false);
  const [loadingGroups, setLoadingGroups] = useState(true);

  // Voice related states
  const [voices, setVoices] = useState<Voice[]>([]);
  const [loadingVoices, setLoadingVoices] = useState(true);

  // Load Avatar Groups
  useEffect(() => {
    const loadAvatarGroups = async () => {
      try {
        setLoadingGroups(true);
        const groups = await avatarService.getAvatarGroups();
        // Prioritize user's private avatar groups
        const sortedGroups = groups.sort((a: AvatarGroup, b: AvatarGroup) => {
          if (a.group_type === 'PRIVATE' && b.group_type !== 'PRIVATE') return -1;
          if (b.group_type === 'PRIVATE' && a.group_type !== 'PRIVATE') return 1;
          if (a.group_type === 'PHOTO' && b.group_type !== 'PHOTO') return -1;
          if (b.group_type === 'PHOTO' && a.group_type !== 'PHOTO') return 1;
          return a.name.localeCompare(b.name);
        });
        setAvatarGroups(sortedGroups);
      } catch (error) {
        console.error('Failed to load avatar groups:', error);
      } finally {
        setLoadingGroups(false);
      }
    };

    loadAvatarGroups();
  }, []);

  // Load Voices
  useEffect(() => {
    const loadVoices = async () => {
      try {
        setLoadingVoices(true);
        const voiceList = await previewService.getVoices();
        setVoices(voiceList);
      } catch (error) {
        console.error('Failed to load voices:', error);
      } finally {
        setLoadingVoices(false);
      }
    };

    loadVoices();
  }, []);

  // Load Avatars in Group
  const loadAvatarsInGroup = async (groupId: string) => {
    if (!groupId) return;

    try {
      setLoadingAvatars(true);
      const avatars = await avatarService.getAvatarsInGroup(groupId);
      setAvatarsInGroup(avatars);
    } catch (error) {
      console.error('Failed to load avatars in group:', error);
      setAvatarsInGroup([]);
    } finally {
      setLoadingAvatars(false);
    }
  };

  // Handle group selection
  const handleGroupSelect = (groupId: string) => {
    setSelectedGroupId(groupId);
    setSelectedAvatar(null);
    setFormData({
      ...formData,
      avatar_id: undefined,
      talking_photo_id: undefined,
      voice_id: undefined, // Clear previous voice selection
    });
    loadAvatarsInGroup(groupId);
  };

  // Handle Avatar selection
  const handleAvatarSelect = (avatar: Avatar) => {
    setSelectedAvatar(avatar);

    // Determine whether to use avatar_id or talking_photo_id based on group type
    const selectedGroup = avatarGroups.find(g => g.group_id === selectedGroupId);
    const isPhotoType =
      selectedGroup?.group_type === 'PHOTO' ||
      selectedGroup?.group_type === 'PUBLIC_PHOTO' ||
      selectedGroup?.group_type === 'COMMUNITY_PHOTO';

    const newFormData = { ...formData };

    if (isPhotoType) {
      newFormData.talking_photo_id = avatar.avatar_id;
      newFormData.avatar_id = undefined;
    } else {
      newFormData.avatar_id = avatar.avatar_id;
      newFormData.talking_photo_id = undefined;
    }

    // Auto-select voice if avatar has default voice
    if (avatar.default_voice_id) {
      newFormData.voice_id = avatar.default_voice_id;
    }

    setFormData(newFormData);
  };

  const updateFormData = (data: Partial<VideoGenerateRequest>) => {
    setFormData(prev => ({ ...prev, ...data }));
  };

  const handleSubmit = async () => {
    if (!formData.title?.trim()) {
      toast.warning('请输入视频标题');
      setActiveTab('script');
      return;
    }

    if (!formData.script.trim()) {
      toast.warning('请输入视频脚本');
      setActiveTab('script');
      return;
    }

    if (formData.script.length > 1500) {
      toast.warning('脚本长度超过1500字符限制，请缩减内容');
      setActiveTab('script');
      return;
    }

    if (!formData.avatar_id && !formData.talking_photo_id) {
      toast.warning('请选择一个数字人形象');
      setActiveTab('avatar');
      return;
    }

    try {
      setGenerating(true);
      const response = await videoService.generateVideo(formData);

      // Save video ID and show status tracker
      setGeneratedVideoId(response.video_id);
      setShowStatusTracker(true);
      setGenerating(false);

      if (onSuccess) {
        onSuccess(response.video_id);
      }
    } catch (error) {
      console.error('Failed to generate video:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      toast.error(`视频生成失败: ${errorMessage}`);
      setGenerating(false);
    }
  };

  // Check if all required fields are filled
  const isValid = {
    title: !!formData.title?.trim(),
    script: !!formData.script.trim() && formData.script.length <= 1500,
    avatar: !!(formData.avatar_id || formData.talking_photo_id),
  };

  // Sidebar navigation items with required field indicators
  const navItems = [
    {
      id: 'script',
      label: '脚本内容',
      icon: Type,
      hasError: !isValid.title || !isValid.script,
    },
    {
      id: 'avatar',
      label: '数字人选择',
      icon: Image,
      hasError: !isValid.avatar,
    },
    {
      id: 'voice',
      label: '语音配置',
      icon: Mic,
      hasError: false,
    },
    {
      id: 'settings',
      label: '视频设置',
      icon: Settings,
      hasError: false,
    },
  ];

  return (
    <>
      {/* Video Status Tracker */}
      {showStatusTracker && generatedVideoId && (
        <VideoStatusTracker
          videoId={generatedVideoId}
          onClose={() => {
            setShowStatusTracker(false);
            setGeneratedVideoId(null);
            onClose();
          }}
        />
      )}

      {/* Video Generate Dialog */}
      {!showStatusTracker && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg w-full max-w-6xl h-[85vh] min-h-[600px] overflow-hidden flex flex-col">
            {/* Header */}
            <div className="p-6 border-b flex justify-between items-center">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
                  <Sparkles className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-gray-900">AI 视频生成器</h2>
                  <p className="text-sm text-gray-600">请按步骤完成必填项配置</p>
                </div>
              </div>
              <button
                onClick={onClose}
                className="text-gray-500 hover:text-gray-700 cursor-pointer"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 flex overflow-hidden">
              {/* Sidebar */}
              <div className="w-52 bg-gray-50 border-r">
                <nav className="p-4 space-y-2">
                  {navItems.map(item => {
                    const Icon = item.icon;
                    return (
                      <button
                        key={item.id}
                        onClick={() => setActiveTab(item.id)}
                        className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium cursor-pointer ${
                          activeTab === item.id
                            ? 'bg-blue-100 text-blue-700'
                            : 'text-gray-700 hover:bg-gray-100 hover:text-gray-900'
                        }`}
                      >
                        <Icon className="w-4 h-4" />
                        <span className="flex-1 text-left">{item.label}</span>
                        {item.hasError && <span className="w-2 h-2 bg-red-500 rounded-full"></span>}
                      </button>
                    );
                  })}
                </nav>
              </div>

              {/* Main Panel */}
              <div className="flex-1 p-6 overflow-y-auto">
                {activeTab === 'script' && (
                  <ScriptTab formData={formData} onChange={updateFormData} />
                )}

                {activeTab === 'avatar' && (
                  <AvatarTab
                    formData={formData}
                    avatarGroups={avatarGroups}
                    avatarsInGroup={avatarsInGroup}
                    selectedGroupId={selectedGroupId}
                    loadingGroups={loadingGroups}
                    loadingAvatars={loadingAvatars}
                    onGroupSelect={handleGroupSelect}
                    onAvatarSelect={handleAvatarSelect}
                  />
                )}

                {activeTab === 'voice' && (
                  <VoiceTab
                    formData={formData}
                    selectedAvatar={selectedAvatar}
                    voices={voices}
                    loadingVoices={loadingVoices}
                    onChange={updateFormData}
                  />
                )}

                {activeTab === 'settings' && (
                  <SettingsTab formData={formData} onChange={updateFormData} />
                )}
              </div>

              {/* Preview Panel */}
              <PreviewPanel
                formData={formData}
                selectedAvatar={selectedAvatar}
                voiceOptions={convertVoicesToOptions(voices)}
              />
            </div>

            {/* Footer */}
            <div className="p-6 border-t flex justify-between items-center">
              <div className="text-sm text-gray-700">
                <span className="inline-flex items-center gap-1 font-medium">
                  <Video className="w-4 h-4" />
                  预计消耗：1-2 积分
                </span>
              </div>
              <div className="flex gap-3">
                <button
                  onClick={onClose}
                  className="px-4 py-2 border border-gray-300 text-gray-800 font-medium rounded-lg hover:bg-gray-50 cursor-pointer"
                >
                  取消
                </button>
                <button
                  onClick={handleSubmit}
                  disabled={generating || !isValid.title || !isValid.script || !isValid.avatar}
                  className="px-4 py-2 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer"
                >
                  {generating ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></div>
                      生成中...
                    </>
                  ) : (
                    <>
                      <Sparkles className="w-4 h-4" />
                      生成视频
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
